// pages/detail/detail.js
import util from "../../../utils/util.js"
//import  amapFile from '../../libs/amap-wx.130'
var QQMapWX  = require("../../../utils/qqmap/qqmap-wx-jssdk.min")
var demo = new QQMapWX({
    key: '3F3BZ-2MT6X-SBG4O-7ZUFM-E6PAO-OXB3Q' // 必填
});

//import amap from '../../libs/amap'
let my_city = ""
let my_district = ""
let my_schoolname = ""
let Openid = ""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    collected: undefined,
    subscried: undefined,
    subscried_wenzi: "开放报名通知我",
    item: {}
  },

  getMenuButtonRect() {
    const { top, right, bottom, width, height } =
      wx.getMenuButtonBoundingClientRect();
    this.setData({
      capsuleTop: top,
      capsuleRight: right,
      capsuleBottom: bottom,
      capsuleWidth: width,
      capsuleHeight: height,
      paddingRight: 375 - right,
    });
  },

changeSub(){
  const that = this
  console.log("that:",that.data.subscried)
  wx.cloud.callFunction({
    name: "getOpenid",
    success(res) {
      console.log("获取openid成功", res.result.openid)
      Openid = res.result.openid

      if(that.data.subscried === false){
        let item = that.data.item
        wx.$cloud.callFunction({
          name: 'userModule',
          data:{
            action:'addSubscribe',
            idnum: 0,
            city: item.city,
            post_level: item.post_level,
            subject: item.subject,
            has_organize: item.has_organized,
            openid: Openid,
          },
          success:(res)=>{
            wx.showLoading({
              title: '订阅成功！',
              duration:1000
            })
            that.setData({
              subscried: true,
              subscried_wenzi:"取消订阅"
            })
          }
        })
      }else{
        wx.$cloud.callFunction({
          name: 'userModule',
          data:{
            action:'deleteSubscribe',
            idnum: 0,
            openid: Openid,
          },
          success:(res)=>{
            wx.showLoading({
              title: '取消成功!',
              duration:1000
            })
            that.setData({
              subscried: false,
              subscried_wenzi:"开放报名通知我"
            })
          }
        })
      }
    },
    fail(res){
      console.log(res)
    }
  })
},

  deleteCollection() {
    var app = getApp();
    wx.$cloud.callFunction({
      name: "userModule",
      data: {
        action: "delete_collection",
        openid: app.globalData.openId,
        curr_id: this.data.item._id,
        type: 0
      },
      success: res => {
        console.log(res, "删除成功")
      }
    })
  },

  subcribed(){
    let subcribed = !that.data.subcribed
  },

  Collect() {
    var that = this;
    wx.cloud.callFunction({
      name: "getOpenid",
      success:res=> {
        console.log("获取openid成功[1]", res)
        console.log("获取openid成功[2]", res.result.openid)
        Openid = res.result.openid
        // 获取“收藏”后选择是哪种云函数
        if(!that.data.collected){
          wx.$cloud.callFunction({
            name: "userModule",
            data: {
              action: "add_collection",
              openid: Openid,
              newcollection: that.data.item._id,
              type: 0
            },
            success(res){
              const c = !that.data.collected
              that.setData({ collected: c })
              console.log('收藏成功：'+res)
            }
          })
        }else{
          wx.$cloud.callFunction({
            name: "userModule",
            data: {
              action: "delete_collection",
              openid: Openid,
              curr_id: that.data.item._id,
              type: 0
            },
            success(res){
              const c = !that.data.collected
              that.setData({collected: c})
              console.log('取消收藏：'+res)
            }
          })
        }
      },
      fail(res) {
        console.log("获取openid失败", res)
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
    })
  },

  copyText: function (e) {
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.email,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  call(e) {
    let phone = e.currentTarget.dataset.phone
    console.dir(e.currentTarget.dataset)
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  JumpToOrigin(e) {
    console.log("this.data.item.original_web:", this.data.item.original_web)
    if (!this.data.item.original_web) {
      wx.showToast({
        title: "无原始公告地址信息"
      });
      return;
    }
    wx.clearStorageSync()
    //wx.setStorageSync('original_web', this.data.item.original_web)
    //wx.navigateTo({ url: '/pages/jumping_org/1',})
    wx.$go2('/pages/jumping_org/1?web='+this.data.item.original_web,false)
  },

  JumpToMap(e) {
    let that = this
    console.log("hhh", e.currentTarget.dataset)
    /* let myAmapFun = new amapFile.AMapWX({key:'74b347d40d34abbe59278143243dc942'});
    console.log(myAmapFun);
    let geocoder = new myAmapFun.Geocoder({});
    let marker = new AMapWX.Marker(); */
    //var geocoder = new amap.AMap.Geocoder({});
    const key = '3F3BZ-2MT6X-SBG4O-7ZUFM-E6PAO-OXB3Q';
    /*  let plugin = requirePlugin('routePlan');
     let referer = '掌上教师招告'; */
    const address = e.currentTarget.dataset.address
    /* if (!address) {
      const eventChannel = that.getOpenerEventChannel()
      // 监听propsFunc事件，获取上一页面通过eventChannel传送到当前页面的数据
      eventChannel.on('propsFunc', (props) => {
        props.registration_begin = util.formatTime(new Date(props.registration_begin))
        props.registration_end = util.formatTime(new Date(props.registration_end))
        props.release_time = that.format(props.release_time)

      })
      console.log("-------:", that.data.item)

      console.log("测试my_city!!!", that.data.item.city)
      my_city = that.data.item.city
      my_district = that.data.item.district
      my_schoolname = that.data.item.school_name

      //let temp_address = wx.getStorageSync('my_city')+wx.getStorageSync('my_district')+wx.getStorageSync('my_schoolname')
      let temp_address = String(my_city) + String(my_district) + String(my_schoolname)
      console.log("临时地址是", String(my_city) + String(my_district) + String(my_schoolname))
      wx.setClipboardData({
        data: String(my_city) + String(my_district) + String(my_schoolname),
      })

      wx.hideToast({
        success: (res) => {
          wx.showToast({
            title: "本地址不可直接导航，地址已复制到您的剪贴板",
            duration: 1500,
            icon: 'none'
          })
        },
      });
      return
    } */
    demo.geocoder({
      address:address,
      success:res=> {
        wx.openLocation({
          latitude: res.result.location.lat,
          longitude: res.result.location.lng,
          scale: 28,
          name: address,
      })
      },
      fail: function(res) {
        console.error(res);
        wx.setClipboardData({
          data: String(my_city) + String(my_district) + String(my_schoolname),
        });
        wx.hideToast({
          success: (res) => {
            wx.showToast({
              title: "本地址不可直接导航，地址已复制到您的剪贴板",
              duration: 1500,
              icon: 'none'
            })
          },
        });
      },
      complete: function(res) {
          console.log("complete",res);
      }
    })
   /*  wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        address: address,
        key
      },
      header: {
        'content-type': "application/json" // 默认值
      },
      success(res) {
        console.log("!!!!!!", res)
        console.log(res.data.message == '查询无结果')
        if (res.data.message == '查询无结果') {
          wx.showToast({
            title: "地址格式有误, 请求失败"
          });
          return
        }
        wx.getLocation({
          type: 'gcj02',
          success: function (result) {
            console.log(result.latitude, result.longitude, typeof result.latitude, typeof result.longitude);
            wx.openLocation({
              latitude: res.data.result.location.lat, // 纬度，范围为-90~90，负数表示南纬
              longitude: res.data.result.location.lng, // 经度，范围为-180~180，负数表示西经
              scale: 18, // 缩放比例
              name: address,
              address,
              success: function (r) {
                console.log(r)
              }
            })
          }
        })
      }
    }) */
  },

  /**
     * 返回上一页
     */
    goBack:function(){
      wx.navigateBack({
        delta: 0,
      }) 
    },

  format(release_time) {
    const time_a = util.formatTime(new Date(release_time)) //此时得到形如2021-11-23
    // console.log(time_a)
    const year = time_a.substr(0, 4)
    let month = time_a.substr(5, 2)
    let day = time_a.substr(8, 2)
    //去掉前导0
    if (month[0] == '0') {
      month = month.substring(1)
    }
    if (day[0] == '0') {
      day = day.substring(1)
    }
    const time_b = year + '-' + month + "-" + day  //此时得到形如2021-11-23
    // console.log(time_b)
    return time_b;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const jobId = options.ID
    if (jobId) {
      wx.$cloud.callFunction({
        name:"getPost",
        data: {
          Action:"getDetail",
          id:jobId,
        },
        success: res=> {
          var props = res.result.data
          props.registration_begin = this.format(props.registration_begin)
          props.registration_end = this.format(props.registration_end)
          props.release_time = this.format(props.release_time)
          this.setData({
            item: {
              ...props
            }
          })
          this.getCollectedStatus()
        },
        fail: console.error
      })
    } else {
      const eventChannel = this.getOpenerEventChannel()
      // 监听propsFunc事件，获取上一页面通过eventChannel传送到当前页面的数据
      eventChannel.on('propsFunc', (props) => {
        console.log('getPropsData', props);
        props.registration_begin = util.formatTime(new Date(props.registration_begin))
        props.registration_end = util.formatTime(new Date(props.registration_end))
        props.release_time = this.format(props.release_time)
        this.setData({
          item: {
            ...props
          }
        })
        this.getCollectedStatus()
      })
      console.log("-------:", this.data.item)

      my_city = this.data.item.city
      my_district = this.data.item.district
      my_schoolname = this.data.item.school_name
      // wx.setStorageSync('my_city', this.data.item.city)
      // wx.setStorageSync('my_district', this.data.item.district)
      // wx.setStorageSync('my_schoolname', this.data.item.school_name)
      // console.log("从缓存",wx.getStorageSync('city'))
    }
    this.getMenuButtonRect();
  },

  getCollectedStatus(){
    wx.cloud.callFunction({
      name: "getOpenid",
      success: res => {
        const Openid = res.result.openid
        wx.$cloud.callFunction({
          name: "userModule",
          data: {
            action: "ifCollected",
            openid: Openid,
            currID: this.data.item._id,
            type: 0
          },
          success: res => {
            this.setData({
              collected: res.result
            })
          },
          fail(res){
            console.log(res)
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log(this.data.item._id);
    return {
      query: `id=${this.data.item._id}`,
      title: "分享详情",
      path: 'pages/detail/detail?id=' + this.data.item._id
    }
  }
})